package com.liupaik.pennmarketplace;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;


public class Prefs extends PreferenceActivity { 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState); 
		addPreferencesFromResource(R.menu.preferences);
		
		//CHANGE PASSWORD PREFERENCE
		Preference password = (Preference) findPreference("password");
		password.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			public boolean onPreferenceClick(Preference preference) {
				//Toast.makeText(getBaseContext(),"The custom preference has been clicked",Toast.LENGTH_LONG).show();
            	
				LayoutInflater factory = LayoutInflater.from(Prefs.this);
	            final View textEntryView = factory.inflate(R.layout.password, null);
	                        	
	            new AlertDialog.Builder(Prefs.this)
	            	//.setTitle("Change Password")
	            	//.setMessage("Password")
	                //.setIcon(R.drawable.book)
	                .setView(textEntryView)	                	  
	                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	
	                    	EditText oldpass = (EditText)textEntryView.findViewById(R.id.oldpass);
	                    	EditText newpass = (EditText)textEntryView.findViewById(R.id.newpass);
	                    	EditText newpass2 = (EditText)textEntryView.findViewById(R.id.newpass2);
	                    	
	                    	String oldp = encrypt(oldpass.getText().toString());
	                    	String newp = encrypt(newpass.getText().toString());
	                    	String newp2 = encrypt(newpass2.getText().toString());
	        				SharedPreferences user = getSharedPreferences("Users", MODE_PRIVATE);
	        		        String id = user.getString("CurrentUser", null);
	                    	
	                    	//PASSWORDS DO NOT MATCH
	                    	if(!newp.equals(newp2)){
	                    		new AlertDialog.Builder(Prefs.this)	                			  
	                			.setMessage("New passwords do not match!")  
	                			.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
	                				public void onClick(DialogInterface dialog, int id) {
	                				}
	                			})
	                			.show();
	                    	}
	                    	
	                    	else if(newpass.getText().toString().length() < 4) {
	                    		
	                    		new AlertDialog.Builder(Prefs.this)	                			  
	                			.setMessage("Password must be at least 4 characters.")  
	                			.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
	                				public void onClick(DialogInterface dialog, int id) {
	                				}
	                			})
	                			.show();
	                    		
	                    	}
	                    	
	                    	
	                    	//PASSWORDS MATCH!
	                    	else{
	                    		String result = password(id,oldp,newp);
	                    		
	                    		//SUCCESS!
	                    		if(result.equals("New password set!")){
	                    			new AlertDialog.Builder(Prefs.this)	                			  
		                			.setMessage(result)  
		                			.setPositiveButton("Nice!", new DialogInterface.OnClickListener() {
		                				public void onClick(DialogInterface dialog, int id) {
		                				}
		                			})
		                			.show();
	                    		}
	                    		
	                    		//WRONG PASSWORD OR CONNECTION ERROR
	                    		else{
	                    			new AlertDialog.Builder(Prefs.this)	                			  
		                			.setMessage(result)  
		                			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		                				public void onClick(DialogInterface dialog, int id) {
		                				}
		                			})
		                			.show();
	                    		}
	                    	}
	                    }
	                })
	                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    }
	                })
	                .show();
				return true;
			}

		});

	}

	public static final String PASSWORD = "http://www.upennakpsi.org/lololol/pennmarketplace/password.php"; 

	private String password(String id, String oldp, String newp) {

		InputStream is = null;

		String returnString = "";

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));
		nameValuePairs.add(new BasicNameValuePair("oldp",oldp));
		nameValuePairs.add(new BasicNameValuePair("newp",newp));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(PASSWORD);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			returnString = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			returnString=sb.toString();
		}catch(Exception e){
			//returnString += "\nError in converting...";
			Log.e("log_tag", "Error converting result "+e.toString());
		}

		return returnString;
	}   
	
	public String encrypt(String password){
		String algorithm = "SHA";

		byte[] plainText = password.getBytes();

		MessageDigest md = null;

		try {		
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			e.printStackTrace();
		}

		md.reset();		
		md.update(plainText);
		byte[] encodedPassword = md.digest();

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				sb.append("0");
			}

			sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}
		return sb.toString();
	}
}
